﻿using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Caching;
using System.Data.SqlClient;
using System.Data;
using System.IO;
using System.ComponentModel;
using System.Web.Security;
using DotNetNuke;
using DotNetNuke.Common;
using DotNetNuke.Services;
using DotNetNuke.Services.Localization;

[assembly: TagPrefix("BeeldBank.Toolkit", "bb")]

namespace BeeldBank.Toolkit
{

    [ToolboxData("<{0}:SearchPagingControl runat=server></{0}:SearchPagingControl>")]
    public class SearchPagingControl : System.Web.UI.WebControls.WebControl
    {

        protected System.Web.UI.WebControls.Table tablePageNumbers;
        protected System.Web.UI.WebControls.Repeater PageNumbers;
        protected System.Web.UI.WebControls.TableCell cellDisplayStatus;
        protected System.Web.UI.WebControls.TableCell cellDisplayLinks;

        private int TotalPages = -1;

        private int _TotalRecords;
        private int _PageSize;
        private int _PageLinksPerPage;
        private int _CurrentPage;
        private string _QuerystringParams;
        private int _TabID;
        private string _CSSClassLinkActive;
        private string _CSSClassLinkInactive;
        private string _CSSClassPagingStatus;
        private bool _WideLayout = true;
        private string _CellWidth;

        [Bindable(true), Category("Behavior"), DefaultValue("0")]
        public int TotalRecords
        {
            get { return _TotalRecords; }

            set { _TotalRecords = value; }
        }
        [Bindable(true), Category("Behavior"), DefaultValue("true")]
        public bool WideLayout
        {
            get { return _WideLayout; }

            set { _WideLayout = value; }
        }
        [Bindable(true), Category("Behavior"), DefaultValue("10")]
        public int PageSize
        {
            get { return _PageSize; }

            set { _PageSize = value; }
        }
        [Bindable(true), Category("Behavior"), DefaultValue("10")]
        public int PageLinksPerPage
        {
            get { return _PageLinksPerPage; }

            set { _PageLinksPerPage = value; }
        }
        [Bindable(true), Category("Behavior"), DefaultValue("1")]
        public int CurrentPage
        {
            get { return _CurrentPage; }

            set { _CurrentPage = value; }
        }
        [Bindable(true), Category("Behavior"), DefaultValue("")]
        public string QuerystringParams
        {
            get { return _QuerystringParams; }

            set { _QuerystringParams = value; }
        }
        [Bindable(true), Category("Behavior"), DefaultValue("-1")]
        public int TabID
        {
            get { return _TabID; }

            set { _TabID = value; }
        }
        [Bindable(true), Category("Behavior"), DefaultValue("Normal")]
        public string CSSClassLinkActive
        {
            get
            {
                if (string.IsNullOrEmpty(_CSSClassLinkActive))
                {
                    return "CommandButton";
                }
                else
                {
                    return _CSSClassLinkActive;
                }
            }

            set { _CSSClassLinkActive = value; }
        }
        [Bindable(true), Category("Behavior"), DefaultValue("CommandButton")]
        public string CSSClassLinkInactive
        {
            get
            {
                if (string.IsNullOrEmpty(_CSSClassLinkInactive))
                {
                    return "NormalDisabled";
                }
                else
                {
                    return _CSSClassLinkInactive;
                }
            }

            set { _CSSClassLinkInactive = value; }
        }
        [Bindable(true), Category("Behavior"), DefaultValue("Normal")]
        public string CSSClassPagingStatus
        {
            get
            {
                if (string.IsNullOrEmpty(_CSSClassPagingStatus))
                {
                    return "Normal";
                }
                else
                {
                    return _CSSClassPagingStatus;
                }
            }

            set { _CSSClassPagingStatus = value; }
        }
        [Bindable(true), Category("Layout"), DefaultValue("50%")]
        public string CellWidth
        {
            get { return _CellWidth; }

            set { _CellWidth = value; }
        }

        protected override void CreateChildControls()
        {
            tablePageNumbers = new System.Web.UI.WebControls.Table();
            cellDisplayStatus = new System.Web.UI.WebControls.TableCell();
            cellDisplayLinks = new System.Web.UI.WebControls.TableCell();
            cellDisplayStatus.CssClass = "Normal";
            cellDisplayLinks.CssClass = "Normal";

            if (string.IsNullOrEmpty(this.CssClass))
            {
                tablePageNumbers.CssClass = "SearchPagingTable";
            }
            else
            {
                tablePageNumbers.CssClass = this.CssClass;
            }

            int intRowIndex = tablePageNumbers.Rows.Add(new TableRow());

            PageNumbers = new Repeater();
            PageNumberLinkTemplate I = new PageNumberLinkTemplate(this);
            PageNumbers.ItemTemplate = I;
            BindPageNumbers(TotalRecords, PageSize);

            int intTotalPages = TotalPages;
            if (intTotalPages == 0) intTotalPages = 1;

            string str = null;
            str = string.Format(Localization.GetString("Pages"), CurrentPage.ToString(), intTotalPages.ToString());
            LiteralControl lit = new LiteralControl(str);
            cellDisplayStatus.Controls.Add(lit);

            tablePageNumbers.Rows[intRowIndex].Cells.Add(cellDisplayStatus);

            cellDisplayStatus.HorizontalAlign = HorizontalAlign.Left;
            if (WideLayout)
            {
                cellDisplayStatus.Width = new Unit(CellWidth);
                cellDisplayLinks.HorizontalAlign = HorizontalAlign.Right;
                cellDisplayLinks.Width = new Unit(CellWidth);
                tablePageNumbers.Rows[intRowIndex].Cells.Add(cellDisplayLinks);
            }
            else
            {
                cellDisplayStatus.Width = new Unit(CellWidth);
                cellDisplayLinks.HorizontalAlign = HorizontalAlign.Left;
                cellDisplayLinks.Width = new Unit(CellWidth);
                cellDisplayLinks.Wrap = false;
                tablePageNumbers.Rows.Add(new TableRow());
                tablePageNumbers.Rows[intRowIndex + 1].Cells.Add(cellDisplayLinks);
            }
        }

        protected override void Render(System.Web.UI.HtmlTextWriter output)
        {
            if (PageNumbers == null)
            {
                CreateChildControls();
            }

            System.Text.StringBuilder str = new System.Text.StringBuilder();

            str.Append(GetFirstLink() + " ");
            str.Append(GetPreviousLink() + " ");
            System.Text.StringBuilder result = new System.Text.StringBuilder(1024);
            PageNumbers.RenderControl(new HtmlTextWriter(new System.IO.StringWriter(result)));
            str.Append(result.ToString());
            str.Append(GetNextLink() + " ");
            str.Append(GetLastLink() + " ");
            cellDisplayLinks.Controls.Add(new LiteralControl(str.ToString()));

            tablePageNumbers.RenderControl(output);
        }

        private void BindPageNumbers(int TotalRecords, int RecordsPerPage)
        {
            if (RecordsPerPage == 0) RecordsPerPage = 10;

            if (TotalRecords / RecordsPerPage >= 1)
            {
                TotalPages = Convert.ToInt32(Math.Ceiling((double)TotalRecords / RecordsPerPage));
            }
            else
            {
                TotalPages = 0;
            }

            if (TotalPages > 0)
            {
                DataTable ht = new DataTable();
                ht.Columns.Add("PageNum");
                DataRow tmpRow = default(DataRow);

                int LowNum = 1;
                int HighNum = (int)TotalPages;

                double tmpNum = 0;
                tmpNum = CurrentPage - PageLinksPerPage / 2;
                if (tmpNum < 1) tmpNum = 1;

                if (CurrentPage > (PageLinksPerPage / 2))
                {
                    LowNum = (int)Math.Floor(tmpNum);
                }

                if ((int)TotalPages <= PageLinksPerPage)
                {
                    HighNum = (int)TotalPages;
                }
                else
                {
                    HighNum = LowNum + PageLinksPerPage - 1;
                }

                if (HighNum > (int)TotalPages)
                {
                    HighNum = (int)TotalPages;
                    if (HighNum - LowNum < PageLinksPerPage)
                    {
                        LowNum = HighNum - PageLinksPerPage + 1;
                    }
                }

                if (HighNum > (int)TotalPages) HighNum = (int)TotalPages;
                if (LowNum < 1) LowNum = 1;

                int i = 0;
                for (i = LowNum; i <= HighNum; i++)
                {
                    tmpRow = ht.NewRow();
                    tmpRow["PageNum"] = i;
                    ht.Rows.Add(tmpRow);
                }

                PageNumbers.DataSource = ht;
                PageNumbers.DataBind();
            }
        }

        private string CreateURL(string CurrentPage)
        {
            if (!string.IsNullOrEmpty(QuerystringParams))
            {
                if (!string.IsNullOrEmpty(CurrentPage))
                {
                    return DotNetNuke.Common.Globals.NavigateURL(TabID, "", QuerystringParams, "searchpage=" + CurrentPage);
                }
                else
                {
                    return DotNetNuke.Common.Globals.NavigateURL(TabID, "", QuerystringParams);
                }
            }
            else
            {
                if (!string.IsNullOrEmpty(CurrentPage))
                {
                    return DotNetNuke.Common.Globals.NavigateURL(TabID, "", "searchpage=" + CurrentPage);
                }
                else
                {
                    return DotNetNuke.Common.Globals.NavigateURL(TabID);
                }
            }
        }

        /// ----------------------------------------------------------------------------- 
        /// <summary> 
        /// GetLink returns the page number links for paging. 
        /// </summary> 
        /// <remarks> 
        /// </remarks> 
        /// <history> 
        /// [dancaron] 10/28/2004 Initial Version 
        /// </history> 
        /// ----------------------------------------------------------------------------- 
        private string GetLink(int PageNum)
        {
            if (PageNum == CurrentPage)
            {
                return "<span class=\"" + CSSClassLinkInactive + "\">[" + PageNum.ToString() + "]</span>";
            }
            else
            {
                return "<a href=\"" + CreateURL(PageNum.ToString()) + "\" class=\"" + CSSClassLinkActive + "\">" + PageNum.ToString() + "</a>";
            }
        }

        /// ----------------------------------------------------------------------------- 
        /// <summary> 
        /// GetPreviousLink returns the link for the Previous page for paging. 
        /// </summary> 
        /// <remarks> 
        /// </remarks> 
        /// <history> 
        /// [dancaron] 10/28/2004 Initial Version 
        /// </history> 
        /// ----------------------------------------------------------------------------- 
        private string GetPreviousLink()
        {
            if (CurrentPage > 1 && TotalPages > 0)
            {
                return "<a href=\"" + CreateURL((CurrentPage - 1).ToString()) + "\" class=\"" + CSSClassLinkActive + "\">" + DotNetNuke.Services.Localization.Localization.GetString("Previous", DotNetNuke.Services.Localization.Localization.SharedResourceFile) + "</a>";
            }
            else
            {
                return "<span class=\"" + CSSClassLinkInactive + "\">" + DotNetNuke.Services.Localization.Localization.GetString("Previous", DotNetNuke.Services.Localization.Localization.SharedResourceFile) + "</span>";
            }
        }

        /// ----------------------------------------------------------------------------- 
        /// <summary> 
        /// GetNextLink returns the link for the Next Page for paging. 
        /// </summary> 
        /// <remarks> 
        /// </remarks> 
        /// <history> 
        /// [dancaron] 10/28/2004 Initial Version 
        /// </history> 
        /// ----------------------------------------------------------------------------- 
        private string GetNextLink()
        {
            if (CurrentPage != TotalPages & TotalPages > 0)
            {
                return "<a href=\"" + CreateURL((CurrentPage + 1).ToString()) + "\" class=\"" + CSSClassLinkActive + "\">" + DotNetNuke.Services.Localization.Localization.GetString("Next", DotNetNuke.Services.Localization.Localization.SharedResourceFile) + "</a>";
            }
            else
            {
                return "<span class=\"" + CSSClassLinkInactive + "\">" + DotNetNuke.Services.Localization.Localization.GetString("Next", DotNetNuke.Services.Localization.Localization.SharedResourceFile) + "</span>";
            }
        }

        /// ----------------------------------------------------------------------------- 
        /// <summary> 
        /// GetFirstLink returns the First Page link for paging. 
        /// </summary> 
        /// <remarks> 
        /// </remarks> 
        /// <history> 
        /// [dancaron] 10/28/2004 Initial Version 
        /// </history> 
        /// ----------------------------------------------------------------------------- 
        private string GetFirstLink()
        {
            if (CurrentPage > 1 && TotalPages > 0)
            {
                return "<a href=\"" + CreateURL("1") + "\" class=\"" + CSSClassLinkActive + "\">" + DotNetNuke.Services.Localization.Localization.GetString("First", DotNetNuke.Services.Localization.Localization.SharedResourceFile) + "</a>";
            }
            else
            {
                return "<span class=\"" + CSSClassLinkInactive + "\">" + DotNetNuke.Services.Localization.Localization.GetString("First", DotNetNuke.Services.Localization.Localization.SharedResourceFile) + "</span>";
            }
        }

        /// ----------------------------------------------------------------------------- 
        /// <summary> 
        /// GetLastLink returns the Last Page link for paging. 
        /// </summary> 
        /// <remarks> 
        /// </remarks> 
        /// <history> 
        /// [dancaron] 10/28/2004 Initial Version 
        /// </history> 
        /// ----------------------------------------------------------------------------- 
        private string GetLastLink()
        {
            if (CurrentPage != TotalPages & TotalPages > 0)
            {
                return "<a href=\"" + CreateURL(TotalPages.ToString()) + "\" class=\"" + CSSClassLinkActive + "\">" + DotNetNuke.Services.Localization.Localization.GetString("Last", DotNetNuke.Services.Localization.Localization.SharedResourceFile) + "</a>";
            }
            else
            {
                return "<span class=\"" + CSSClassLinkInactive + "\">" + DotNetNuke.Services.Localization.Localization.GetString("Last", DotNetNuke.Services.Localization.Localization.SharedResourceFile) + "</span>";
            }
        }

        public class PageNumberLinkTemplate : ITemplate
        {
            private SearchPagingControl _SearchPagingControl;

            public PageNumberLinkTemplate(SearchPagingControl ctlSearchPagingControl)
            {
                _SearchPagingControl = ctlSearchPagingControl;
            }

            public void InstantiateIn(Control container)
            {
                Literal l = new Literal();
                l.DataBinding += this.BindData;
                container.Controls.Add(l);
            }

            private void BindData(object sender, System.EventArgs e)
            {
                Literal lc = default(Literal);
                lc = (Literal)sender;
                RepeaterItem container = default(RepeaterItem);
                container = (RepeaterItem)lc.NamingContainer;
                lc.Text = _SearchPagingControl.GetLink(Convert.ToInt32(DataBinder.Eval(container.DataItem, "PageNum"))) + " ";
            }
        }
    }
}